package com.tenton.servlet;

import com.tenton.pojo.User;
import com.tenton.service.Impl.UserServiceImpl;
import com.tenton.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Date: 2021/1/19
 * @Author: Tenton
 * @Description: 根据用户Id查询用户信息
 */
@WebServlet(name = "SelectUserByIdServlet",urlPatterns = "/selectUserByIdServlet")
public class SelectUserByIdServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //用户Id
        String userId = request.getParameter("id");
        Integer id = null;
        //判断是否为空，然后再进行转化为int类型
        if(userId !=null && !userId.equals("")){
            id = Integer.parseInt(userId);
        }
        UserService userService = new UserServiceImpl();
        if (id != null) {
            //根据用户Id查询用户信息
            User user = userService.getUserById(id);
            //存到request域中，传递给前端
            request.setAttribute("user", user);
            //请求跳转
            request.getRequestDispatcher("/getUserById.jsp").forward(request, response);
        }else {
            response.sendRedirect("/listUserServlet");
            return;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
